package com.leetcodehot.problems;

import java.util.Arrays;

public class problems16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int n = nums.length;
        //相差是多少，最终值是target+res，res = sum-target
        //负 比target小多少
        //正 比target大多少
        boolean flag = false;

        int res = Integer.MAX_VALUE;
        for (int i = 0; i < n - 2; i++) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == target) {
                    return target;
                } else if (sum < target) {
                    if (Math.abs(sum - target) < res) {
                        flag = false;
                        res = Math.abs(sum - target);
                    }
                    j++;
                } else {
                    //sum>target
                    if (Math.abs(sum - target) < res) {
                        flag = true;
                        res = Math.abs(sum - target);

                    }
                    k--;
                }
            }
        }
        return flag ? target + res : target - res;
    }
}
